package gcb.metalsys.service.cop.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import gcb.metalsys.base.exception.AbtBaseException;
import gcb.metalsys.entity.auth.AuthUser;
import gcb.metalsys.entity.cop.CopDepartment;
import gcb.metalsys.entity.cop.CopProduct;
import gcb.metalsys.enums.UploadEnum;
import gcb.metalsys.exception.UploadException;
import gcb.metalsys.mapper.cop.CopDepartmentMapper;
import gcb.metalsys.service.auth.AuthUserService;
import gcb.metalsys.service.cop.CopDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2019-12-24
 */
@Service
public class CopDepartmentServiceImpl extends ServiceImpl<CopDepartmentMapper, CopDepartment> implements CopDepartmentService {

    @Autowired
    private AuthUserService authUserService;

    @Override
    public void readExcel(MultipartFile multipartFile) throws RuntimeException {
        String filePath = multipartFile.getOriginalFilename();

        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream inputStream = null;
        Workbook workbook = null;
        List<CopDepartment> departmentList = new ArrayList<>();

        try {
            inputStream = multipartFile.getInputStream();
            if (".xls".equals(extString)) {
                workbook = new HSSFWorkbook(inputStream);
            } else if (".xlsx".equals(extString)) {
                workbook = new XSSFWorkbook(inputStream);
            }

            Sheet sheet = workbook.getSheetAt(0);
            int rows = sheet.getLastRowNum() + 1;
            Row tmp = sheet.getRow(0);
            int cols = tmp.getPhysicalNumberOfCells();

            for (int row = 1; row < rows; row++) {
                Row r = sheet.getRow(row);
                CopDepartment department = new CopDepartment(new Long(r.getCell(0).getStringCellValue()),r.getCell(1).getStringCellValue(),
                        new Long(r.getCell(2).getStringCellValue()));
                departmentList.add(department);
            }

            List<String> nameList = departmentList.stream().map(CopDepartment::getDepartmentName).collect(Collectors.toList());
            QueryWrapper<CopProduct> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("department_name",nameList);
            List<CopDepartment> existList = list();

            for (CopDepartment department : existList) {
                for (CopDepartment department1 : departmentList) {
                    if (department1.getDepartmentName().equals(department.getDepartmentName())) {
                        department1.setDepartmentId(department.getDepartmentId());
                        break;
                    }
                }
            }
            saveOrUpdateBatch(departmentList);
        } catch (Exception e) {
            throw new UploadException(UploadEnum.ERROR);
        }
    }

    @Override
    public List<CopDepartment> getMyselfAndChildId(Authentication authentication) throws Exception {
        if(authentication == null){
            return null;
        }
        AuthUser userDetails = authUserService.getUserDetails(authentication);
        List<CopDepartment> userList = new ArrayList<>();
        CopDepartment myself = getById(userDetails.getUserDepartment());
        userList.add(myself);
        List<CopDepartment> child = getChild(userList);

        return  child;
    }

    private  List<CopDepartment>  getChild(List<CopDepartment> users){
        List<Long> department = users.stream().map(CopDepartment::getDepartmentId).collect(Collectors.toList());
        QueryWrapper<CopDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("department_parent",department);
        List<CopDepartment> child = list(queryWrapper);
        if (!child.isEmpty()){
            child = getChild(child);
            child.addAll(users);
            return child;
        }
        return users;
    }

    private CopDepartment getMyself(Long id){
        return getById(id);
    }

}
